﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Linq;

namespace WxPayAPI
{
    /// <summary>
    /// 支付结果通知回调处理类
    /// 负责接收微信支付后台发送的支付结果并对订单有效性进行验证，将验证结果反馈给微信支付后台
    /// </summary>
    public class ResultNotify : Notify
    {
        public ResultNotify(Page page) : base(page) { }

        /// <summary>
        /// 业务处理，并将结果返回回微信支付
        /// </summary>
        public override void ProcessNotify()
        {
            Log.Error(this.GetType().ToString(), "收到微信的ProcessNotify回调信息");

            WxPayData notifyData = GetNotifyData();
            //检查支付结果中transaction_id是否存在
            if (!notifyData.IsSet("transaction_id"))
            {
                //若transaction_id不存在，则立即返回结果给微信支付后台
                WxPayData res = new WxPayData();
                res.SetValue("return_code", "FAIL");
                res.SetValue("return_msg", "支付结果中微信订单号不存在");
                Log.Error(this.GetType().ToString(), "The Pay result is error : " + res.ToXml());
                page.Response.Write(res.ToXml());
                page.Response.End();
            }
            string transaction_id = notifyData.GetValue("transaction_id").ToString();
            lock (this)
            {
                //查询订单，判断订单真实性
                if (!QueryOrder(transaction_id))
                {
                    //若订单查询失败，则立即返回结果给微信支付后台
                    //WxPayData res = new WxPayData();
                    //res.SetValue("return_code", "FAIL");
                    //res.SetValue("return_msg", "订单查询失败");
                    //Log.Error(this.GetType().ToString(), "Order query failure : " + res.ToXml());
                    //page.Response.Write(res.ToXml());
                    //page.Response.End();
                    //page.Response.Write("222222222222222");
                    page.Response.Redirect("/Order/Fail");
                }
                //查询订单成功
                else
                {
                    //WxPayData res = new WxPayData();
                    //res.SetValue("return_code", "SUCCESS");
                    //res.SetValue("return_msg", "OK");
                    //Log.Info(this.GetType().ToString(), "order query success : " + res.ToXml());
                    //page.Response.Write(res.ToXml());
                    //page.Response.End();

                    //page.Response.Write("111111111111111111");
                    page.Response.Redirect("/Order/Sucess");

                }
            }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="transaction_id"></param>
        /// <returns></returns>
        //查询订单
        private bool QueryOrder(string transaction_id)
        {
            WxPayData req = new WxPayData();
            req.SetValue("transaction_id", transaction_id);
            WxPayData res = WxPayApi.OrderQuery(req);
            if (res.GetValue("return_code").ToString() == "SUCCESS" &&
                res.GetValue("result_code").ToString() == "SUCCESS")
            {
                Log.Error(this.GetType().ToString(), "==================回调处理订单开始===========");

                int orderId = Convert.ToInt32(res.GetValue("attach").ToString());
                Log.Error(this.GetType().ToString(), "==================ResultNotify-----订单号:" + orderId + "===========");

                try
                {
                    //Order order = OrderService.GetOrder(orderId);
                    //order.State = CommonCode.订单状态_未发货;
                    //order.PayWay = CommonCode.支付类型_微信;
                    //order.Trade_No = transaction_id;
                    //order.PayTime = DateTime.Now;

                    //Log.Error(this.GetType().ToString(), "transaction_id:" + transaction_id);
                    //Log.Error(this.GetType().ToString(), "order.State:" + order.State);
                    //Log.Error(this.GetType().ToString(), "order.PayWay:" + order.PayWay);
                    //Log.Error(this.GetType().ToString(), "order.Trade_No:" + order.Trade_No);
                    //Log.Error(this.GetType().ToString(), "StaticData.CurrentUser.Name:" + StaticData.CurrentUser.Name);
                    //Log.Error(this.GetType().ToString(), "StaticData.CurrentUser.ID:" + StaticData.CurrentUser.ID);

                    //OrderService.SaveOrder(order, "微信支付订单，流水号：" + transaction_id + "  订单编号：" + orderId + " 用户ID：" + order.UserId + "  支付订单成功状态为《未发货》状态");

                    Log.Error(this.GetType().ToString(), "==================ResultNotify-----订单支付回调完成===========");
                }
                catch (Exception ex)
                {
                    Log.Error(this.GetType().ToString(), "==================ResultNotify-----订单支付回调失败:" + ex.Message + "===========");
                }


                return true;
            }
            else
            {
                Log.Error(this.GetType().ToString(), "==================订单回调外部查询失败数据start===========");
                Log.Error(this.GetType().ToString(), "订单回调外部查询失败" + res.ToXml());
                Log.Error(this.GetType().ToString(), "==================订单回调外部查询失败数据end===========");
                return false;
            }
        }
    }
}